//
//  DashedLineView.swift
//  JJToolSwift
//
//  Created by heihei on 2024/6/30.
//
//  虚线view

import UIKit

public class DashedLineView: UIView {

    /// 控制横竖向虚线的属性，是否是横向
    @IBInspectable public var isHorizontal: Bool = true {
        didSet {
            setNeedsDisplay()
        }
    }
    
    /// 线条颜色
    @IBInspectable public var dashColor: UIColor = .lightGray {
        didSet {
            setNeedsDisplay()
        }
    }
    
    /// 线条宽度
    @IBInspectable public var dashWidth: CGFloat = 1.0 {
        didSet {
            setNeedsDisplay()
        }
    }
    
    /// 实线长度
    @IBInspectable public var lineLength: CGFloat = 7 {
        didSet {
            dashPattern = [lineLength, blankDis]
        }
    }
    /// 空白长度
    @IBInspectable public var blankDis: CGFloat = 7 {
        didSet {
            dashPattern = [lineLength, blankDis]
        }
    }
    
    /// 线条的模式，默认实线长度7，间隔空白长度7
    public var dashPattern: [CGFloat] = [7, 7] {
        didSet {
            setNeedsDisplay()
        }
    }
    
    public override func draw(_ rect: CGRect) {
        super.draw(rect)
        
        guard let context = UIGraphicsGetCurrentContext() else { return }
        
        context.setStrokeColor(dashColor.cgColor)
        context.setLineWidth(dashWidth)
        context.setLineDash(phase: 0, lengths: dashPattern.map { $0 })
        
        if isHorizontal {
            context.move(to: CGPoint(x: rect.minX, y: rect.midY))
            context.addLine(to: CGPoint(x: rect.maxX, y: rect.midY))
        } else {
            context.move(to: CGPoint(x: rect.midX, y: rect.minY))
            context.addLine(to: CGPoint(x: rect.midX, y: rect.maxY))
        }
        
        context.strokePath()
    }

}
